package com.linxianqin.springbootVue.controller.system;

import com.linxianqin.springbootVue.domain.constant.UserConstants;
import com.linxianqin.springbootVue.domain.convert.SysDeptConvert;
import com.linxianqin.springbootVue.domain.dto.SysDeptDTO;
import com.linxianqin.springbootVue.domain.enums.BusinessType;
import com.linxianqin.springbootVue.domain.model.AjaxResult;
import com.linxianqin.springbootVue.domain.query.SysDeptQuery;
import com.linxianqin.springbootVue.manage.annotation.SysLog;
import com.linxianqin.springbootVue.manage.core.BaseController;
import com.linxianqin.springbootVue.service.SysDeptService;
import com.linxianqin.springbootVue.service.SysUserService;
import com.linxianqin.springbootVue.utils.SecurityUtils;
import com.linxianqin.springbootVue.utils.text.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * @author lxq
 * @version 1.0
 * @description: 部门信息
 * @date 2020/12/16 10:55
 */
@Slf4j
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController {
    private final SysDeptService deptService;
    private final SysUserService sysUserService;
    public SysDeptController(SysDeptService deptService,SysUserService sysUserService){
        this.deptService=deptService;
        this.sysUserService=sysUserService;
    }

    /**
     * 获取部门列表
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list")
    public AjaxResult list(SysDeptQuery query)
    {
        List<SysDeptDTO> dtoList = deptService.selectDeptList(query);
        return AjaxResult.success(dtoList);
    }
    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId)
    {
        List<SysDeptDTO> deptDTOS = deptService.excludeChild(deptId);
        return AjaxResult.success(deptDTOS);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId)
    {
        return AjaxResult.success(SysDeptConvert.INSTANCE.entity2dto(deptService.getById(deptId)));
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysDeptQuery query)
    {
        List<SysDeptDTO> deptList = deptService.selectDeptList(query);
        return AjaxResult.success(deptService.buildDeptTreeSelect(deptList));
    }
    /**
     * 新增部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @SysLog(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDeptDTO deptDTO)
    {
        //校验部门名称是否唯一
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(deptDTO)))
        {
            return AjaxResult.error("新增部门'" + deptDTO.getDeptName() + "'失败，部门名称已存在");
        }
        deptDTO.setCreateBy(SecurityUtils.getUsername());
        return toAjax(deptService.insertDept(deptDTO));
    }


    /**
     * 修改部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @SysLog(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDeptDTO deptDTO)
    {
        //校验部门名称是否唯一
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(deptDTO)))
        {
            return AjaxResult.error("修改部门'" + deptDTO.getDeptName() + "'失败，部门名称已存在");
        }
        else if (deptDTO.getParentId().equals(deptDTO.getDeptId()))
        {
            return AjaxResult.error("修改部门'" + deptDTO.getDeptName() + "'失败，上级部门不能是自己");
        }
        //根据ID查询所有子部门（正常状态）
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, deptDTO.getStatus())
                && deptService.selectNormalChildrenDeptById(deptDTO.getDeptId()) > 0)
        {
            return AjaxResult.error("该部门包含未停用的子部门！");
        }
        deptDTO.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(deptService.updateById(SysDeptConvert.INSTANCE.dto2entity(deptDTO)));
    }
    /**
     * 删除部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @SysLog(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId)
    {
        if (deptService.hasChildByDeptId(deptId))
        {
            return AjaxResult.error("存在下级部门,不允许删除");
        }
        if (sysUserService.checkDeptExistUser(deptId))
        {
            return AjaxResult.error("部门存在用户,不允许删除");
        }
        return toAjax(deptService.removeById(deptId));
    }

}
